import smtplib
from email.mime.text import MIMEText
from email.header import Header
import socket
import os
import re


class ClamAV(object):
    ## 这里填入自己的远程smtp服务。利用第三方smtp服务进行邮件发送。
    def __init__(self):
        self.HOST = "smtp.exmail.qq.com"
        self.PORT = "465"
        self.USER = 'xxx@xxxx.com'
        self.PASSWD = 'xxxxxx'
        self.TO = "xxxxxxxxx@xx.com"

    def clamscan(self):
        os.system('freshclam')
        os.system('clamscan -ri /tmp > /tmp/clamscan.log')
        with open('/tmp/clamscan.log', 'r', encoding='utf-8') as f:
            a = f.read()

        result = re.findall('Infected files:.*', a)
        if result:
            number = result[0].split(':')[1].strip()
            if number != '0':
                self.sendmail('Infected files:%s。有文件感染，请手动检查，查杀病毒。' % number)
        else:
            self.sendmail('扫描脚本有误，请检查')

    def sendmail(self, content):
        ipaddr = socket.gethostbyname(socket.gethostname())

        smtp = smtplib.SMTP_SSL(self.HOST, self.PORT)
        smtp.ehlo()
        smtp.login(self.USER, self.PASSWD)

        TEXT = """IP: %s\nContent: %s""" % (ipaddr, content)
        message = MIMEText(TEXT, 'plain', 'utf-8')
        message['From'] = self.USER
        message['To'] = self.TO
        message['Subject'] = Header('Clamscan Result Warning', 'utf-8')

        smtp.sendmail(self.USER, self.TO, message.as_string())
        smtp.quit()


clam = ClamAV()
clam.clamscan()

## 每天凌晨四点执行
# vim /etc/crontab
#
# 00 4 * * * root {local-path}/clamsacn.py